package com.xiaoshuidi.cloud.framework.excel.core.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.xiaoshuidi.cloud.framework.common.pojo.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * Excel 工具类
 *
 * @author
 */
@Slf4j
public class ExcelUtils {

    /**
     * 将列表以 Excel 响应给前端
     *
     * @param response 响应
     * @param filename 文件名
     * @param sheetName Excel sheet 名
     * @param head Excel head 头
     * @param data 数据列表哦
     * @param <T> 泛型，保证 head 和 data 类型的一致性
     * @throws IOException 写入失败的情况
     */
    public static <T> void write(HttpServletResponse response, String filename, String sheetName,
                                 Class<T> head, List<T> data) throws IOException {
        // 输出 Excel
        EasyExcel.write(response.getOutputStream(), head)
                .autoCloseStream(false) // 不要自动关闭，交给 Servlet 自己处理
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) // 基于 column 长度，自动适配。最大 255 宽度
                .sheet(sheetName).doWrite(data);
        // 设置 header 和 contentType。写在最后的原因是，避免报错时，响应 contentType 已经被修改了
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
    }

    public static <T> List<T> read(MultipartFile file, Class<T> head) throws IOException {
       return EasyExcel.read(file.getInputStream(), head, null)
                .autoCloseStream(false)  // 不要自动关闭，交给 Servlet 自己处理
                .doReadAllSync();
    }

    /**
     * 分页导出
     * @param response
     * @param fileName 导出文件名
     * @param sheetName sheet名
     * @param head 表头
     * @param page 分页数据
     * @param nextPage 下一页数据
     * @param <T>
     * @throws IOException
     */
    public static <R, T> void write(HttpServletResponse response, String fileName, String sheetName,
                                Class<T> head, PageResult<R> page, Function<List<R>, List<T>> listConvert,
                                Function<Integer, PageResult<R>> nextPage) throws IOException {
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        try (ExcelWriter w = EasyExcel.write(response.getOutputStream())
                .autoCloseStream(false)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).build()) {
            WriteSheet sheet = EasyExcel.writerSheet(sheetName).head(head).build();
            if (page.getTotal() == 0) {
                w.write(new ArrayList<>(0), sheet);
                return;
            }
            int pageNo = 1;
            while(CollectionUtils.isNotEmpty(page.getList())) {
                w.write(listConvert.apply(page.getList()), sheet);
                pageNo++;
                page = nextPage.apply(pageNo);
            }
        }
    }

    /**
     * 填充模板
     * @param response
     * @param fileName 导出文件名
     * @param template 模板文件流
     * @param page 分页数据
     * @param listConvert 分页数据转换
     * @param nextPage 下一页
     * @param additionalFill 其它需要填充的数据
     * @param <R> 原始数据
     * @param <T> 目标数据
     * @throws IOException
     */
    public static <R, T> void fill(HttpServletResponse response, String fileName, InputStream template, PageResult<R> page, Function<List<R>, List<T>> listConvert,
                                   Function<Integer, PageResult<R>> nextPage, Supplier<Object> additionalFill) throws IOException {
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream())
                .autoCloseStream(false).withTemplate(template).build()) {
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            if (page.getTotal() > 0) {
                FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
                int pageNo = 1;
                while (CollectionUtils.isNotEmpty(page.getList())) {
                    excelWriter.fill(listConvert.apply(page.getList()), fillConfig, writeSheet);
                    pageNo++;
                    page = nextPage.apply(pageNo);
                }
            }
            excelWriter.fill(additionalFill.get(), writeSheet);
        } catch (Exception e) {
            log.error("", e);
        }
    }

}
